package com.bluefox.uac.service.impl;

import com.bluefox.common.web.exception.CustomRuntimeException;
import com.bluefox.uac.model.User;
import com.bluefox.uac.repository.UserRepository;
import com.bluefox.uac.service.UserService;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * UserService 实现类
 *
 * @author SunFeng
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    @Transactional(readOnly = true)
    public User get(@NonNull Long id) {
        final User model = userRepository.findById(id).get();
        if (model == null) {
            throw new CustomRuntimeException("404", String.format("查找的资源[%s]不存在.", id));
        }
        return model;
    }

    @Override
    public User create(User model) {
        // TODO: 业务逻辑
        model.setEnable(1);
        User byUsername = this.userRepository.findByUsername(model.getUsername());
        if(null!=byUsername){
            throw new CustomRuntimeException("400","该用户已经存在");
        }
        return userRepository.save(model);
    }

    @Override
    public User update(User model) {
        // TODO: 业务逻辑
        return userRepository.save(model);
    }

    @Override
    public void delete(@NonNull Long id) {
        // TODO: 业务逻辑
        userRepository.deleteById(id);
    }

    @Override
    public User findByUserName(String userName) {
        return userRepository.findByUsername(userName);
    }

    @Override
    public List<String> getUserRoles(String roleList) {
        // 后期数据库获取权限  权限前面要ROLE_
        List<String> roles = new ArrayList<>();
        if (roleList.toLowerCase().equals("admin")){
            roles.add("ROLE_ADMIN");
        }
        roles.add("ROLE_USER");
        return roles;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatePass(String username, String pass) {
        userRepository.updatePass(username,pass);
    }
}
